package family.yaongteam.connectlines;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;

public class Paper {

	private View view;
	// PointInfo
	private List<PointInfo> pointInfoList = new ArrayList<PointInfo>();

	// Image
	private Bitmap paperImage;
	private PointNumberType numberType;
	private float xRatio = 1;
	private float yRatio = 1;
	private boolean isFirstDraw = true;
	
	public Paper(View view){
		this.view = view;
		//resetPoint();
	}
	
	// 해상도에 따른 좌표 이동
	public void resetPoint(){
		float vw = view.getWidth();
		float vh = view.getHeight();
		float pw = paperImage.getWidth();
		float ph = paperImage.getHeight();
		
		xRatio = vw/pw;
		yRatio = vh/ph;
		
		if(xRatio == 0 ) xRatio = 1;
		if(yRatio == 0 ) yRatio = 1;
		
		for(int i=0;i<pointInfoList.size();i++)
		{
			PointInfo pi = pointInfoList.get(i);
			pi.setxRatio(xRatio);
			pi.setyRatio(yRatio);			
		}
	}
	
	public List<PointInfo> getPointInfoList() {
		return pointInfoList;
	}

	public void setPointInfoList(List<PointInfo> pointInfoList) {
		this.pointInfoList = pointInfoList;
	}
	
	public void setPaperImage(int imageId){
		paperImage = BitmapFactory.decodeResource(view.getResources(), imageId);
	}
	
	// 이미지 그리기, 포인트 그리기, 선 긋기
	public void draw(Canvas canvas, Paint paint, int curStartNum, boolean isDone){
		if(isFirstDraw){
			resetPoint();
			isFirstDraw = false;
		}
		if(isDone){
			canvas.drawBitmap(paperImage, null, getImageRect(), null);
		}
		
		for(int i=0;i<pointInfoList.size();i++)
		{
			PointInfo pi = pointInfoList.get(i);
			pi.setNumber(i);
			pi.setUse(false);
			if(i<=curStartNum){
				pi.setUse(true);
			}
			
			if(i>0 && i<=curStartNum)
			{
				PointInfo prev = pointInfoList.get(i-1);
				paint.setColor(Color.GREEN);
				canvas.drawLine(prev.getX(), prev.getY(), pi.getX(), pi.getY(), paint);
			}
			
			pi.draw(canvas);
		}		
	}
	
	public Rect getImageRect(){
		int left=0, top=0, right=0, bottom = 0;

		right = view.getWidth();
		bottom = view.getHeight();
		
		if(view.getHeight() > view.getWidth()){
			// 세로 해상도 portrait
			if(paperImage.getWidth() > view.getWidth()){
				// 이미지 세로가 더 길 경우, view 길이에 맞춘다. 
				//right = 
			}
			
		} else {
			// 가로 해상도 landscape
			
		}
	 
		Log.d("paperImage.getWidth",Integer.toString(paperImage.getWidth()));
		Log.d("paperImage.getHeight",Integer.toString(paperImage.getHeight()));
		Log.d("view.getWidth",Integer.toString(view.getWidth()));
		Log.d("view.getHeight",Integer.toString(view.getHeight()));
			
		return new Rect(left,top,right,bottom);
	}
}
